var permissionCodes = [];
var ctx;

$(function () {
    ctx = $("#ctx").val();

    $(document).on("keydown", function (e) {
        var btnClose = $("div.layui-layer-dialog .layui-layer-btn .layui-layer-btn0");
        if (e.which === 13 && btnClose.length > 0 && btnClose.text() === "确定") {
            btnClose.click();
            return false;
        }
    });

    if (sessionStorage.getItem("sysPermissionCodes") == null && sessionStorage.getItem("sysSessionUser") == null) {
        $.ajax({
            url: ctx + "/initIndex",
            method: "get",
            async: false,
            success: function (rtn) {
                if (rtn.code != 1) {
                    Alert("获取数据失败");
                    return;
                }
                var data = rtn.data;
                if (data != null) {
                    sessionStorage.setItem("sysPermissionCodes", data["permissionCodes"]);
                    sessionStorage.setItem("sysSessionUser", data["sessionUser"]);
                }
            }
        });
    }

    var ps = sessionStorage.getItem("sysPermissionCodes");
    if (ps != null) {
        permissionCodes = ps.split(",");
    }
    var sessionUser= sessionStorage.getItem("sysSessionUser");
    if (sessionUser != null) {
        $("#sessionUserName").html($.parseJSON(sessionUser)["userName"]);
    }

    // AJAX
    ajaxSetting();
    // 左侧栏设置
    setNavbar();
    // 图片上传预览
    bindImgFile();

    // 点击按钮隐藏显示左侧栏
    /*$(":button.navbar-expand-toggle").click(function (e) {
        $("div.sidebar-inverse").animate({width:"5px"}, "fast");
        $("div.side-body").animate({marginLeft:"-120px"}, "fast");
        $("div.navbar-header").animate({marginLeft:"-200px"}, "normal");
    });*/

    $('.match-height').matchHeight();
    $('.toggle-checkbox').bootstrapSwitch({
        size: "small"
    });
});

function bindImgFile() {
    $(":file[img]").change(function (e) {
        if (window.FileReader) {
            var reader = new FileReader();
        } else {
            Alert("您的设备不支持图片预览功能，如需该功能请升级您的设备！");
        }
        //获取文件
        var fileDom = e.target;
        var file = fileDom.files[0];
        var imageType = /^image\//;
        //是否是图片
        if (!imageType.test(file.type)) {
            Alert("请选择图片！");
            return;
        }
        //读取完成
        reader.onload = function (e) {
            //获取图片dom
            var img = $(fileDom).siblings("img");
            //图片路径设置为读取的图片
            $(img).attr("src", e.target.result);
        };
        reader.readAsDataURL(file);
    });

    $(document).on("click", "img[name='nail-img']", function (e) {
        var $this = $(e.target);
        $this.siblings("input").click();
    });
}

/**
 * 左侧菜单栏
 */
function setNavbar() {

    // 权限判断
    /*$("li.nav_side_menu").each(function (i, v) {
        var id = $(this).attr("id");
        if ($.inArray(id, permissionCodes) < 0) {
            $(this).css("display", "none");
        }
    });*/
    $("div.side-menu-container div.panel-collapse ul.navbar-nav li a").each(function (i, v) {
        var navSideMenu = $(this).parent().parents("li.nav_side_menu");
        if (navSideMenu.css("display") == "none") {
            return;
        }
        var url = $(this).attr("url");
        var location = document.location.href;
        var _manager_url = $("#_manager_url");
        // 列表页面
        if (location.indexOf(url) > -1) {
            $(this).css("color", "#22A7F0");
            $(this).parents("div.panel-collapse").removeClass("collapse").addClass("expanded");
        }
        // 非列表页面
        if (_manager_url.length > 0 && _manager_url.attr("url").indexOf(url) > -1) {
            $(this).css("color", "#22A7F0");
            $(this).parents("div.panel-collapse").removeClass("collapse").addClass("expanded");
        }
    });
    $(document).on("click", "div.side-menu-container div.panel-collapse ul.navbar-nav li", function () {
        var url = $(this).find("a").attr("url");
        document.location.replace(ctx + url);
    });
}

/**
 * ajax加载设置
 */
function ajaxSetting() {
    $(document).ajaxStart(function () {
        var src = ctx + "/public/layer/theme/default/loading-0.gif";
        $.blockUI({message: '<img src="'+ src +'" />'});
    }).ajaxStop(function () {
        $.unblockUI();
    });
}


function hasPermission(pc) {
    /*if (permissionCodes && $.trim(permissionCodes).length > 0) {
        return permissionCodes.indexOf(pc) > -1;
    }
    return false;*/
    return true;
}

/**
 * 弹出框
 * @param msg 提示信息
 * @param callback 回调
 * @constructor
 */
function Alert(msg, callback) {
    if (typeof callback === "function") {
        layer.open({
            content: msg,
            yes: function (index) {
                callback.call(this);
                layer.close(index);
            }
        });
        return;
    }
    layer.alert(msg);
}

/**
 * 确认框
 * @param msg 消息
 * @param callback 回调
 * @constructor
 */
function Confirm(msg, callback) {
    layer.open({
        content: msg,
        btn: ["确定", "取消"],
        btn1: function (index) {
            callback.call(this);
            layer.close(index);
        }
    });
}


/**
 * 自定义StringBuilder
 * @constructor
 */
function StringBuilder () {
    this.__asBuilder = [];
}

StringBuilder.prototype.clear = function(){
    this.__asBuilder = [];//这种写法要比this.__asBuilder.length = 0稍快,快多少，看数组的长度
};

StringBuilder.prototype.append = function(){
    Array.prototype.push.apply(this.__asBuilder,arguments);//调用Array的push方法，这样调用，使用append,可以传递多个参数
    return this;//这样可以实现append("a").append()的效果
};

StringBuilder.prototype.toString = function(){
    return this.__asBuilder.join("");
};

/**
 * 扩展Date对象，增加格式化方法
 * @param format
 * @returns {*}
 */
Date.prototype.format = function(format) {
    var date = {
        "M+": this.getMonth() + 1,
        "d+": this.getDate(),
        "h+": this.getHours(),
        "m+": this.getMinutes(),
        "s+": this.getSeconds(),
        "q+": Math.floor((this.getMonth() + 3) / 3),
        "S+": this.getMilliseconds()
    };

    if (/(y+)/i.test(format)) {
        format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
    }
    for (var k in date) {
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1
                ? date[k] : ("00" + date[k]).substr(("" + date[k]).length));
        }
    }
    return format;
};

function dateFormat(value, format) {
    if (arguments.length == 1) {
        format = 'yyyy-MM-dd';
    }
    return new Date(value).format(format);
}

jQuery.validator.methods.compareDate = function(value, element, param) {
    //var startDate = jQuery(param).val() + ":00";补全yyyy-MM-dd HH:mm:ss格式
    //value = value + ":00";
    var startDate = jQuery(param).val();
    var date1 = new Date(Date.parse(startDate.replace("-", "/")));
    var date2 = new Date(Date.parse(value.replace("-", "/")));
    return date1 < date2;
};